package com.studerb.view;

import static com.studerb.util.Constants.EVENT_SERVICE_NAME;

import org.apache.log4j.Logger;
import org.bushe.swing.event.annotation.AnnotationProcessor;
import org.bushe.swing.event.annotation.EventSubscriber;
import org.springframework.beans.factory.annotation.Autowired;

import com.jidesoft.status.LabelStatusBarItem;
import com.jidesoft.status.MemoryStatusBarItem;
import com.jidesoft.status.StatusBar;
import com.jidesoft.swing.JideBoxLayout;
import com.studerb.events.NetworkMonitorEvent;
import com.studerb.events.ServerEvent;
import com.studerb.service.NetworkMonitorService;
import com.studerb.service.interfaces.IServerService;

public class GnusbinStatusBar extends StatusBar {
	private LabelStatusBarItem networkLabel;
	private LabelStatusBarItem masterServerLabel;
	private MemoryStatusBarItem memoryItem;
	private final String NETWORK_UP = "  Network Up  ";
	private final String NETWORK_DOWN = "  Network Down  ";
	private final String MASTER_DEFINED = "  Master Server Ok  ";
	private final String MASTER_NOT_DEFINED = "  Master Server NOT Ok  ";
	Logger logger = Logger.getLogger(StatusBar.class);
	@Autowired NetworkMonitorService networkMonitorService;
	@Autowired IServerService serverService;

	public void init() {
		setAutoAddSeparator(true);
		networkLabel = new LabelStatusBarItem();
		// networkLabel.setBorder(BorderFactory.createLineBorder(Color.black));
		networkLabel.setText(networkMonitorService.isNetworkUp() ? NETWORK_UP : NETWORK_DOWN);
		networkLabel.setPreferredWidth(100);
		add(networkLabel, JideBoxLayout.FIX);
		masterServerLabel = new LabelStatusBarItem();
		//masterServerLabel.setBorder(BorderFactory.createLineBorder(Color.black
		// ));
		masterServerLabel.setText(serverService.isMasterServerDefined() ? MASTER_DEFINED : MASTER_NOT_DEFINED);
		masterServerLabel.setPreferredWidth(100);
		add(masterServerLabel, JideBoxLayout.FIX);

		memoryItem = new MemoryStatusBarItem();
		memoryItem.setPreferredWidth(300);
		add(memoryItem, JideBoxLayout.FIX);
		// this.setBorder(BorderFactory.createBevelBorder(2));
		AnnotationProcessor.process(this);
	}

	@EventSubscriber(eventServiceName = EVENT_SERVICE_NAME) public void onEvent(NetworkMonitorEvent networkMonitorEvent) {
		logger.debug("Got NetworkMonitorEvent");
		NetworkMonitorEvent.EventType type = networkMonitorEvent.getType();
		switch (type) {
		case NETWORK_UP:
			networkLabel.setText(NETWORK_UP);
			break;
		case NETWORK_DOWN:
			networkLabel.setText(NETWORK_DOWN);
			break;
		default:
			break;
		}
	}

	@EventSubscriber(eventServiceName = EVENT_SERVICE_NAME) public void onEvent(ServerEvent serverEvent) {
		logger.debug("Got ServerEvent");
		if (serverService.isMasterServerDefined()) {
			masterServerLabel.setText(MASTER_DEFINED);
		}
		else {
			masterServerLabel.setText(MASTER_NOT_DEFINED);
		}
	}
}
